package com.googlecode.bipol.war.services;

import java.util.List;

import com.googlecode.bip.dao.QuestionDAO;
import com.googlecode.bip.dao.TopicDAO;
import com.googlecode.bip.entity.IQuestion;
import com.googlecode.bip.entity.ITopic;
import com.googlecode.bip.entity.Question;

public class QuestionManagerImpl implements QuestionManager {

	@Override
	public IQuestion createQuestion(int topicId, String name,
			String description, String idLocal, int minValue, int maxValue,
			int defaultValue) throws ServiceException {
		
		// Get back the topic the question should belongs to
		ITopic topic;
		try {
			topic = new TopicDAO().findTopic(topicId, idLocal);
		} catch(Exception e) {
			throw new ServiceException("Error when getting topic with id \'"+topicId+"\' and local \'"+idLocal+"\': "+e.getMessage());
		}
		if (topic == null) {
			throw new ServiceException("Error: the topic with id \'"+topicId+"\' and local \'"+idLocal+"\' does not exist !");
		}
		// Create the question based on given parameters
		Question q = new Question();
		q.setParentIdTopic(topicId);
		q.setName(name);
		q.setDescription(description);
		q.setMinValue(minValue);
		q.setMaxValue(maxValue);
		q.setDefaultValue(defaultValue);
		q.setIdLocal(idLocal);
		// Insert the new question
		try {
			if (new QuestionDAO().insertQuestion(q)) {
				return q;
			} else {
				throw new ServiceException("Error when saving question: Unknown reason (please contact the administrator)");
			}
		} catch(Exception e) {
			throw new ServiceException("Error when saving question: "+e.getMessage());
		}
	}

}
